<template>
  <div class="cart">
    <el-card>
      <el-table
        :data="cartList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="零件图片" width="100">
          <template #default="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" width="100"></el-table-column>
        <el-table-column prop="partTypeName" label="零件类型名称" width="120"></el-table-column>
        <el-table-column prop="partName" label="零件名称" width="150"></el-table-column>
        <el-table-column prop="supplyPrice" label="供货单价" width="80">
          <template #default="scope">
            ¥{{ scope.row.supplyPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="minOrderQuantity" label="最小起订量" width="80"></el-table-column>
        <el-table-column label="采购数量" width="120">
          <template #default="scope">
            <div class="number-input">
              <el-input-number
                v-model="scope.row.quantity"
                :min="scope.row.minOrderQuantity"
                size="small"
                @change="(value) => handleQuantityChange(scope.row, value - scope.row.quantity)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <el-button
          type="primary"
          :disabled="selectedParts.length === 0"
          @click="handleSubmitOrder"
        >
          提交订单
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const cartList = ref([])
const selectedParts = ref([])

// 获取购物车列表
const getCartList = async () => {
  try {
    const response = await axios.get('/carRepair/admin/partManage/partCart')
    if (response.data.code === 200) {
      cartList.value = response.data.data
    }
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    ElMessage.error('获取购物车列表失败')
  }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedParts.value = selection
}

// 处理数量变化
const handleQuantityChange = async (part, change) => {
  console.log(part)
  const newQuantity = part.quantity + change
  if (newQuantity >= part.minOrderQuantity) {
    try {
      const response = await axios.put('/carRepair/admin/partManage/partCart', {
        relationId: part.partRelationId,
        quantity: newQuantity
      })
      if (response.data.code === 200) {
        part.quantity = newQuantity
        ElMessage.success('数量修改成功')
      } else {
        ElMessage.error(response.data.message || '数量修改失败')
      }
    } catch (error) {
      console.error('修改数量失败:', error)
      ElMessage.error('修改数量失败')
    }
  }
}

// 处理删除
const handleDelete = async (part) => {
  try {
    await ElMessageBox.confirm('确定要删除这个配件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete('/carRepair/admin/partManage/partCart', {
      params: {
        partRelationIds: part.partRelationId
      }
    })
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getCartList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理提交订单
const handleSubmitOrder = async () => {
  try {
    const orderForms = selectedParts.value.map(part => ({
      relationId: part.partRelationId,
      quantity: part.quantity
    }))

    const response = await axios.post('/carRepair/admin/partManage/submitOrder', orderForms)
    if (response.data.code === 200) {
      ElMessage.success('订单提交成功')
      getCartList()
    } else {
      ElMessage.error(response.data.message || '订单提交失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('提交订单失败')
  }
}

onMounted(() => {
  getCartList()
})
</script>

<style scoped>
.cart {
  padding: 0px;
  width: 950px;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-right: 45px;
}

.number-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-input-number) {
  width: 100px;
}

:deep(.el-table__cell) {
  padding: 1px 0;
}
</style>